package com.jl.juc.feature;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * JDK5就有
 * 获取异步任务的执行结果，取消任务等
 */
public class FeatureTaskDemo1 {


    /**
     * FutureTask
     *
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Test
    public void testFeature() throws ExecutionException, InterruptedException {

        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "我是FutureTask返回的结果";
            }
        });

        Thread thread = new Thread(futureTask, "futureTask1");
        thread.start();

        String s = futureTask.get();
        System.out.println(s);

    }

    /**
     * 线程池提交FutureTask
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws TimeoutException
     */
    @Test
    public void testFeatureExecutor() throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        FutureTask<String> futureTask1 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "我是FutureTask返回的结果1";
            }
        });
        executorService.submit(futureTask1);

        FutureTask<String> futureTask2 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "我是FutureTask返回的结果2";
            }
        });

        executorService.submit(futureTask2);

        //get是阻塞的，建议放在程序最后面
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());

        //超时等待
//        System.out.println(futureTask2.get(2, TimeUnit.SECONDS));

        System.out.println("main---sleep");
        Thread.sleep(3000);
        System.out.println("main-------------end");

        executorService.shutdown();

    }


    /**
     * 轮训FutureTask是否执行完成
     * @throws ExecutionException
     * @throws InterruptedException
     * @throws TimeoutException
     */
    @Test
    public void testFeatureExecutorDone() throws ExecutionException, InterruptedException, TimeoutException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        FutureTask<String> futureTask1 = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(3);
                return "我是FutureTask返回的结果1";
            }
        });
        executorService.submit(futureTask1);

        while (true){
            if(futureTask1.isDone()){
                System.out.println(futureTask1.get());
                executorService.shutdown();
                break;
            }else {
                System.out.println("正在轮训任务状态");
                TimeUnit.SECONDS.sleep(1);
            }
        }


    }

}
